#include "TournamentSelect.h"
#include "EvolutionaryAlgorithm.h"
#include "Configuration.h"
#include "RandomGenerator.h"
#include "Printer.h"
#include <vector>
#include <iterator>

EvolutionaryAlgorithm::population_type TournamentSelect::select(int genNo, const EvolutionaryAlgorithm::population_type & actualPopulation)
{
	//tworzenie grupy turniejowej
	//Configuration::tournamentGroupNo = actualPopulation.size();
	unsigned int tourGroupNo = Configuration::tournamentGroupNo;
	if (Configuration::tournamentGroupNo > Configuration::u)
	{
		tourGroupNo = Configuration::u;
	}
	std::vector<Genotype> all = std::vector<Genotype>(actualPopulation.begin(), actualPopulation.end());
	std::set<unsigned int> choosen;
	while (choosen.size() < tourGroupNo)
	{
		unsigned int tmp = _random.getRandom(0, all.size());
		while(choosen.count(tmp) > 0)
		{
			tmp = (tmp + 1) % all.size();
		}
		choosen.insert(tmp);
	}
	std::set<Genotype> tournamentGroup = std::set<Genotype>();
	for (std::set<unsigned int>::const_iterator i = choosen.begin(); i != choosen.end(); ++i)
	{
		tournamentGroup.insert(all.at(*i));
	}

	std::set<Genotype>::iterator it = tournamentGroup.begin();
	std::advance(it,genNo);

	//std::cout<<"select: "<<std::endl;
	//Printer::ciout(tournamentGroup);
	//Printer::ciout(std::set<Genotype>(tournamentGroup.begin(), it));

	return std::set<Genotype>(tournamentGroup.begin(), it);
}
